package los.kael.fixcss;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;

/**
 * 
 * @author kael
 * 
 */
public class FixCss {
	// 文件
	private String inputFilename = "tests/style.css";
	// 前缀
	private String headStr = ".kael ";
	// 编码
	private String charset = "UTF-8";
	// 行
	private String line = "";
	// 注释
	private String ant = "";
	// 注释标记
	private boolean antFlag = false;
	// 结果
	private StringBuffer sb = new StringBuffer();
	// 输出
	private Writer out = null;
	// 精简标记
	private boolean isMin = false;

	/**
	 * 返回要处理的文件
	 * 
	 * @return
	 */
	public String getInputFilename() {
		return inputFilename;
	}

	/**
	 * 设置要处理的文件
	 * 
	 * @param inputFilename
	 */
	public void setInputFilename(String inputFilename) {
		this.inputFilename = inputFilename;
	}

	/**
	 * 设置要添加的前缀
	 * 
	 * @param headStr
	 */
	public void setHeadStr(String headStr) {
		this.headStr = headStr;
	}

	/**
	 * 设置编码
	 * 
	 * @param charset
	 */
	public void setCharset(String charset) {
		this.charset = charset;
	}

	public FixCss() {

	}

	public FixCss(String inputFilename) {
		this.inputFilename = inputFilename;
	}

	public FixCss(String inputFilename, String headStr) {
		this.inputFilename = inputFilename;
		this.headStr = headStr;
	}

	public FixCss(String inputFilename, String headStr, String charset) {
		this.inputFilename = inputFilename;
		this.headStr = headStr;
		this.charset = charset;
	}

	/**
	 * 处理文件 并返回结果
	 * 
	 */
	public FixCss AddHead() {
		InputStreamReader in = null;
		int c;
		try {
			in = new InputStreamReader(new FileInputStream(inputFilename), charset);
			while ((c = in.read()) != -1) {
				// 处理注释
				if (antFlag) {
					ant += (char) c;
					if (ant.indexOf("*/") != -1) {
						// 注释结束
						antFlag = false;
						ant = "";
					}
				} else {
					// '}'为行结束符
					if ((c != '\n') && (c != '}')) {
						line += (char) c;
						if (line.indexOf("/*") != -1) {
							// 遇到注释 暂停获取
							antFlag = true;
							// 清除注释符号
							line = line.replace("/*", "");
						}
						// 处理charset
						if (line.indexOf("@charset") != -1 && line.indexOf(";") != -1) {
							// 保存处理结果
							sb.append(line + '\n');
							// 清空行
							line = "";
						}
					} else {
						// 行结束
						if (c == '}') {
							line += (char) c;
						}
						line = line.trim();
						if (!line.endsWith("}")) {
							continue;
						}
						if (line.matches("[^\n@]+[{},]$")) {
							// 行首添加前缀
							line = headStr + " " + line;
							// 将tab符转成空格
							line = line.replace("\t", " ");
							// 去除逗号后面的空格
							line = line.replace(", ", ",");
							// 为逗号分隔符后标签添加前缀
							line = line.replace(",", "," + headStr + " ");
							// 处理body
							line = line.replace(headStr + " body", "body" + headStr);
							// 处理html
							line = line.replace(headStr + " html", "html");
							// 处理不必要的替换
						}
						// 保存处理结果
						int index = line.indexOf("{");
						if (index != -1) {
							String temp = line.substring(0, index).trim();
							sb.append(temp);
							line = line.substring(index, line.length());
							line = line.replace("," + headStr + " ", ",");
							line = line.replace("; ", ";");
							line = line.replace("{ ", "{");
							line = line.replace(";}", "}");
						}
						sb.append(line + '\n');
						// 清空行
						line = "";
					}
				}
			}
		} catch (Exception e) {
			// 无视一切异常
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return this;
	}

	/**
	 * 将结果写入文件
	 */
	public FixCss WirteTo(String outputFilename) {
		try {
			if (outputFilename == null) {
				out = new OutputStreamWriter(System.out, charset);
			} else {
				out = new OutputStreamWriter(new FileOutputStream(outputFilename), charset);
			}
			// 写入文件
			if (isMin) {
				String minStr = sb.toString().replace("\n", "");
				out.write(minStr, 0, minStr.length());
			} else {
				out.write(sb.toString(), 0, sb.length());
			}
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return this;
	}

	public FixCss WirteTo() {
		return WirteTo(null);
	}

	/**
	 * 以*.min.css为文件名写入磁盘
	 */
	public FixCss WirteToMin() {
		String outputFilename = inputFilename.replace(".css", ".min.css");
		isMin = true;
		return WirteTo(outputFilename);
	}
}
